package com.snsoft.service.environment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.snsoft.bean.Base;
import com.snsoft.dao.EnvironmentDao;
import com.snsoft.exception.BaseNotFound;

/**
 * 
 * @copyright ：神农大学生软件创新中心 版权所有 © 2017
 * 
 * @author 16计算机弓耀
 * 
 * @version 1.0
 * 
 * @date 2017年11月22日下午9:06:46
 * 
 * @Description TODO 获取天气预报信息接口
 */
public class GetForecastService {
	// 获取位置信息
	public List<Base> getBaseList(String userID) throws SQLException, BaseNotFound {
		EnvironmentDao ed = new EnvironmentDao();
		List<Map<String, Object>> list = ed.getCompanyIDList(userID);
		List<Base> result = new ArrayList<Base>();
		if (list.isEmpty()) {
			throw new BaseNotFound("基地不存在");
		}
		for (Map<String, Object> map : list) {
			if (ed.getBaseInfo(Integer.parseInt(map.get("companyID").toString())) != null) {
				result.add(ed.getBaseInfo(Integer.parseInt(map.get("companyID").toString())));
			}
		}
		if (result.isEmpty()) {
			throw new BaseNotFound("基地不存在");
		}

		return result;
	}

	// 获取天气信息
	public String getForecast(String city) throws IOException {
		
		String apiUrl = String.format("http://www.sojson.com/open/api/weather/json.shtml?city=%s", city);
		URL url = new URL(apiUrl);
		URLConnection open = url.openConnection();
		InputStream input = open.getInputStream();
		
		BufferedReader in = new BufferedReader(new InputStreamReader(input));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		while ((line = in.readLine()) != null) {
			buffer.append(line);
		}
		return buffer.toString();
	}
}
